package de.tum.in.eist.poll.client.control;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ButtonBase;

import de.tum.in.eist.poll.client.gui.Dashboard;
import de.tum.in.eist.poll.client.gui.Headline;

public class HeadlineHandler {

	private EIST_POLL eistPoll;
	private Dashboard dashboard;
	private Headline headline;
	private ClickHandler buttonHandler;

	public HeadlineHandler(Dashboard dashboard, EIST_POLL eistPoll,
			Headline headline) {
		this.dashboard = dashboard;
		this.eistPoll = eistPoll;
		this.headline = headline;
		init();
	}

	private void init() {
		buttonHandler = createButtonHandler();
		headline.getNotifyButton().addClickHandler(buttonHandler);
		headline.getOverAllButton().addClickHandler(buttonHandler);
		headline.getSemesterButton().addClickHandler(buttonHandler);
		headline.getCurrentWeekButton().addClickHandler(buttonHandler);
		headline.getLastWeekButton().addClickHandler(buttonHandler);
		headline.getCreateLectureButton().addClickHandler(buttonHandler);
		headline.getLogoutButton().addClickHandler(buttonHandler);
	}

	/**
	 * Create a ClickHandler that handles the different button events
	 * 
	 * @return new ClickHandler
	 */
	private ClickHandler createButtonHandler() {
		return new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				ButtonBase src = (ButtonBase) event.getSource();
				
				for(int i = 0; i < headline.getWidgetCount(); i++)
					headline.getWidget(i).removeStyleName("active");
				src.addStyleName("active");
				
				if (src.equals(headline.getNotifyButton())) {
					dashboard.getWidgetList().selectNotificationsView();
				}
				// This week
				else if (src.equals(headline.getCurrentWeekButton())) {
					dashboard.getWidgetList().selectCurrentWeekView();
				}
				// Last two weeks
				else if (src.equals(headline.getLastWeekButton())) {
					dashboard.getWidgetList().selectLastWeekView();
				}
				// Select range
				else if (src.equals(headline.getSemesterButton())) {
					dashboard.getWidgetList().selectSemesterView();
				}
				// Over all Statistic
				else if (src.equals(headline.getOverAllButton())) {
					if (!dashboard.isOverAllChartVisible()) {
						dashboard.updateOverAllChart();
						dashboard.getOverAllChart().setVisible(true);
						headline.addActiveStyleNameTo(headline.getOverAllButton());
					} else {
						dashboard.getOverAllChart().setVisible(false);
						headline.removeActiveStyleNameFrom(headline.getOverAllButton());
					}
				}
				// Logout
				else if (src.equals(headline.getLogoutButton())) {
					eistPoll.setUser(null); // Set an empty user
					Cookies.removeCookie("EIST_POLL_SESSIONID");
					eistPoll.loadLoginForm();
				}
			}
		};
	}
}
